/**
 * Created by fky on 4/4/2018.
 */
import {Injectable} from '@angular/core';
import {HttpInterceptor, HttpHandler, HttpRequest, HttpEvent} from '@angular/common/http';
import {Md5} from 'ts-md5/dist/md5'
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import {NbTokenService} from '@nebular/auth/services/token/token.service'
import 'rxjs/add/operator/switchMap';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {


  constructor(private nbTokenService: NbTokenService) {

  }


  intercept(req: HttpRequest<any>,
            next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.url === '/api/oauth/token') {
      const requestCopy = req.clone({
          headers: req.headers
            .append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
            .append('authorization', 'Basic dGVzdGp3dGNsaWVudGlkOlhZN2ttem9OemwxMDA='),
          body: 'username=' + req.body.email + '&password=' + Md5.hashStr(req.body.password) + '&grant_type=password',
        },
      );
      return next.handle(requestCopy);
    } else if (req.url === '/api/user/register') {
      const requestCopy = req.clone({
          body: {
            email: req.body.email,
            userName: req.body.userName,
            password: Md5.hashStr(req.body.password),
            confirmPassword: Md5.hashStr(req.body.confirmPassword),
            terms: req.body.terms,
          },
        },
      );
      return next.handle(requestCopy);
    } else {
      return this.nbTokenService.get().switchMap(tokenObj => {
        const token = tokenObj.getValue();
        const requestCopy = req.clone({
          headers: req.headers
            .append('Authorization', 'Bearer ' + token),
        });
        return next.handle(requestCopy);
      });
    }
  }
}
